package com.pai4j.pay.config.interceptor;

import com.pai4j.pay.config.annotation.ValidateAccessPaymentPermission;
import com.pai4j.pay.config.exception.PaymentAccessAuthException;
import com.pai4j.pay.service.PaymentApiService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 基于拦截器实现自定义注解 @ValidateAccessPaymentPermission
 * 作用：完成支付对外三方API请求统一鉴权、优雅实现鉴权逻辑解耦
 */
@Slf4j
public class ValidateAccessPaymentPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private PaymentApiService paymentApiService;

    /**
     * 鉴权逻辑：
     *
     * 1、从当前请求头中获取token参数
     * 2、对token实现有效性校验
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        ValidateAccessPaymentPermission validateAccessPaymentPermission =
                method.getAnnotation(ValidateAccessPaymentPermission.class);
        if (validateAccessPaymentPermission == null) {
            // 当前请求不需要校验token
            return true;
        }
        // 从当前请求http中获取token参数
        String token = request.getHeader("access-token");
        boolean validateResult = paymentApiService.validateAccessToken(token);
        if (validateResult) {
            return true;
        }
        // 支付服务请求token无权限
        throw new PaymentAccessAuthException("交易凭证校验失败");
    }
}
